define([], function () {
    require(['fast', 'layer'], function (Fast, Layer) {
    var _fastOpen = Fast.api.open;
    Fast.api.open = function (url, title, options) {
        options = options || {};
        options.area = Config.betterform.area;
        options.offset = Config.betterform.offset;
        options.anim = Config.betterform.anim;
        options.shadeClose = Config.betterform.shadeClose;
        options.shade = Config.betterform.shade;
        return _fastOpen(url, title, options);
    };
    if (isNaN(Config.betterform.anim)) {
        var _layerOpen = Layer.open;
        Layer.open = function (options) {
            var classNameArr = {slideDown: "layer-anim-slide-down", slideLeft: "layer-anim-slide-left", slideUp: "layer-anim-slide-up", slideRight: "layer-anim-slide-right"};
            var animClass = "layer-anim " + classNameArr[options.anim] || "layer-anim-fadein";
            var index = _layerOpen(options);
            var layero = $('#layui-layer' + index);

            layero.addClass(classNameArr[options.anim] + "-custom");
            layero.addClass(animClass).one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function () {
                $(this).removeClass(animClass);
            });
            return index;
        }
    }
});
require(['../addons/bootstrapcontextmenu/js/bootstrap-contextmenu'], function (undefined) {
    if (Config.controllername == 'index' && Config.actionname == 'index') {
        $("body").append(
            '<div id="context-menu">' +
            '<ul class="dropdown-menu" role="menu">' +
            '<li><a tabindex="-1" data-operate="refresh"><i class="fa fa-refresh fa-fw"></i>刷新</a></li>' +
            '<li><a tabindex="-1" data-operate="refreshTable"><i class="fa fa-table fa-fw"></i>刷新表格</a></li>' +
            '<li><a tabindex="-1" data-operate="close"><i class="fa fa-close fa-fw"></i>关闭</a></li>' +
            '<li><a tabindex="-1" data-operate="closeOther"><i class="fa fa-window-close-o fa-fw"></i>关闭其他</a></li>' +
            '<li class="divider"></li>' +
            '<li><a tabindex="-1" data-operate="closeAll"><i class="fa fa-power-off fa-fw"></i>关闭全部</a></li>' +
            '</ul>' +
            '</div>');

        $(".nav-addtabs").contextmenu({
            target: "#context-menu",
            scopes: 'li[role=presentation]',
            onItem: function (e, event) {
                var $element = $(event.target);
                var tab_id = e.attr('id');
                var id = tab_id.substr('tab_'.length);
                var con_id = 'con_' + id;
                switch ($element.data('operate')) {
                    case 'refresh':
                        $("#" + con_id + " iframe").attr('src', function (i, val) {
                            return val;
                        });
                        break;
                    case 'refreshTable':
                        try {
                            if ($("#" + con_id + " iframe").contents().find(".btn-refresh").size() > 0) {
                                $("#" + con_id + " iframe")[0].contentWindow.$(".btn-refresh").trigger("click");
                            }
                        } catch (e) {

                        }
                        break;
                    case 'close':
                        if (e.find(".close-tab").length > 0) {
                            e.find(".close-tab").click();
                        }
                        break;
                    case 'closeOther':
                        e.parent().find("li[role='presentation']").each(function () {
                            if ($(this).attr('id') == tab_id) {
                                return;
                            }
                            if ($(this).find(".close-tab").length > 0) {
                                $(this).find(".close-tab").click();
                            }
                        });
                        break;
                    case 'closeAll':
                        e.parent().find("li[role='presentation']").each(function () {
                            if ($(this).find(".close-tab").length > 0) {
                                $(this).find(".close-tab").click();
                            }
                        });
                        break;
                    default:
                        break;
                }
            }
        });
    }
    $(document).on('click', function () { // iframe内点击 隐藏菜单
        try {
            top.window.$(".nav-addtabs").contextmenu("closemenu");
        } catch (e) {
        }
    });

});
//判断系统深色模式变化，修改切换按钮
var matchMedia = window.matchMedia(('(prefers-color-scheme: dark)'));
matchMedia.addEventListener('change', function () {
    var mode = this.matches ? 'dark' : 'light';
    //只有当cookie中无手动定义值时才进行操作
    if (document.cookie.indexOf("thememode=") === -1 && Config.darktheme.mode === 'auto') {
        $("body").toggleClass("darktheme", mode === "dark");
    }
});

if (typeof Config.darktheme !== 'undefined' && Config.darktheme.switchbtn) {

    // 切换模式
    var switchMode = function (mode) {
        // 获取当前深色模式
        if (mode === 'auto') {
            var isDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches;
            mode = isDarkMode ? 'dark' : 'light';
        }

        if (mode === 'auto') {
        } else if (mode === 'dark') {
            $("body").addClass("darktheme");
            $(".darktheme-link").removeAttr("media");
        } else {
            $("body").removeClass("darktheme");
            $(".darktheme-link").attr("media", "(prefers-color-scheme: dark)");
        }
    };

    // 创建Cookie
    var createCookie = function (name, value) {
        var date = new Date();
        date.setTime(date.getTime() + (365 * 24 * 60 * 60 * 1000));
        var url = Config.moduleurl.replace(location.origin, "");
        var path = url ? url.substring(url.lastIndexOf("/")) : "/";
        document.cookie = encodeURIComponent(Config.cookie.prefix + name) + "=" + encodeURIComponent(value) + "; path=" + path + "; expires=" + date.toGMTString();
    };

    if (Config.controllername === 'index' && Config.actionname === 'index') {
        var mode = Config.darktheme.mode;
        if (mode === 'auto') {
            var isDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches;
            mode = isDarkMode ? 'dark' : 'light';
        }
        var html = '<li class="theme-li">' +
            '<button type="button" title="切换' + (mode === 'dark' ? '浅色' : '深色') + '模式" data-mode="' + (mode === 'dark' ? 'light' : 'dark') + '" class="theme-toggle">' +
            '<svg class="sun-and-moon" aria-hidden="true" width="24" height="24" viewBox="0 0 24 24">\n' +
            '      <circle class="sun" cx="12" cy="12" r="6" mask="url(#moon-mask)" fill="currentColor" />\n' +
            '      <g class="sun-beams" stroke="currentColor">\n' +
            '        <line x1="12" y1="1" x2="12" y2="3" />\n' +
            '        <line x1="12" y1="21" x2="12" y2="23" />\n' +
            '        <line x1="4.22" y1="4.22" x2="5.64" y2="5.64" />\n' +
            '        <line x1="18.36" y1="18.36" x2="19.78" y2="19.78" />\n' +
            '        <line x1="1" y1="12" x2="3" y2="12" />\n' +
            '        <line x1="21" y1="12" x2="23" y2="12" />\n' +
            '        <line x1="4.22" y1="19.78" x2="5.64" y2="18.36" />\n' +
            '        <line x1="18.36" y1="5.64" x2="19.78" y2="4.22" />\n' +
            '      </g>\n' +
            '      <mask class="moon" id="moon-mask">\n' +
            '        <rect x="0" y="0" width="100%" height="100%" fill="white" />\n' +
            '        <circle cx="24" cy="10" r="6" fill="black" />\n' +
            '      </mask>\n' +
            '    </svg>' +
            '</button>' +
            '</li>';
        $(html).prependTo("#firstnav > div > ul");

        //点击切换按钮
        $(document).on("click", ".theme-toggle", function () {
            var mode = $(this).attr("data-mode");
            switchMode(mode);
            createCookie("thememode", mode);
            $("iframe").each(function () {
                try {
                    $(this)[0].contentWindow.$("body").trigger("swithmode", [mode]);
                } catch (e) {

                }
            });
            $(this).attr("data-mode", mode === 'dark' ? 'light' : 'dark').attr("title", '切换' + (mode === 'dark' ? '浅色' : '深色') + '模式');
        });

        //判断系统深色模式变化，修改切换按钮
        var matchMedia = window.matchMedia(('(prefers-color-scheme: dark)'));
        matchMedia.addEventListener('change', function () {
            var mode = this.matches ? 'dark' : 'light';
            //只有当cookie中无手动定义值时才切换
            if (document.cookie.indexOf("thememode=") === -1 && Config.darktheme.mode === 'auto') {
                $(".theme-toggle").attr("data-mode", mode === 'dark' ? 'light' : 'dark').attr("title", '切换' + (mode === 'dark' ? '浅色' : '深色') + '模式');
            }
        });
    } else {
        //添加事件
        $("body").on("swithmode", function (e, mode) {
            switchMode(mode);
            $("iframe").each(function () {
                try {
                    $(this)[0].contentWindow.$("body").trigger("swithmode", [mode]);
                } catch (e) {

                }
            });
        });
    }
}
require.config({
    paths: {
        'bootstrap-markdown': '../addons/markdown/js/bootstrap-markdown.min',
        'hyperdown': '../addons/markdown/js/hyperdown.min',
        'turndown': '../addons/markdown/js/turndown',
    },
    shim: {
        'bootstrap-markdown': {
            deps: [
                'jquery',
                'css!../addons/markdown/css/bootstrap-markdown.css'
            ],
            exports: '$.fn.markdown'
        }
    }
});
require(['form', 'upload'], function (Form, Upload) {
    var _bindevent = Form.events.bindevent;
    Form.events.bindevent = function (form) {
        _bindevent.apply(this, [form]);
        var insert = function (e, url, type) {
            var urlArr = url.split(/\,/);
            $.each(urlArr, function () {
                var url = Fast.api.cdnurl(this, true);
                if (type && type == 'image') {
                    e.replaceSelection("\n" + '![输入图片说明](' + url + ')');
                } else {
                    e.replaceSelection("\n" + '[输入链接说明](' + url + ')');
                }
            });
            e.change(e);
            // e.$element.blur();
            // e.$element.focus();
        };
        try {
            if ($(Config.markdown.classname || '.editor', form).length > 0) {
                require(['bootstrap-markdown', 'hyperdown', 'turndown'], function (undefined, undefined, Turndown) {
                    $.fn.markdown.messages.zh = {
                        Bold: "粗体",
                        Italic: "斜体",
                        Heading: "标题",
                        "URL/Link": "链接",
                        Image: "图片",
                        List: "列表",
                        "Unordered List": "无序列表",
                        "Ordered List": "有序列表",
                        Code: "代码",
                        Quote: "引用",
                        Preview: "预览",
                        "strong text": "粗体",
                        "emphasized text": "强调",
                        "heading text": "标题",
                        "enter link description here": "输入链接说明",
                        "Insert Hyperlink": "URL地址",
                        "enter image description here": "输入图片说明",
                        "Insert Image Hyperlink": "图片URL地址",
                        "enter image title here": "在这里输入图片标题",
                        "list text here": "这里是列表文本",
                        "code text here": "这里输入代码",
                        "quote here": "这里输入引用文本"
                    };
                    var parser = new HyperDown();
                    window.marked = function (text) {
                        return parser.makeHtml(text);
                    };
                    var uploadFiles;
                    uploadFiles = async function (files) {
                        var self = this;
                        for (var i = 0; i < files.length; i++) {
                            try {
                                await new Promise((resolve) => {
                                    var url, html, file;
                                    file = files[i];
                                    Upload.api.send(file, function (data) {
                                        url = Fast.api.cdnurl(data.url, true);
                                        if (file.type.indexOf("image") !== -1) {
                                            insert(self, url, 'image');
                                        } else {
                                            insert(self, url, 'file');
                                        }
                                        resolve();
                                    }, function () {
                                        resolve();
                                    });
                                });
                            } catch (e) {

                            }
                        }
                    };

                    $(Config.markdown.classname || '.editor', form).each(function () {
                        var options = $(this).data("markdown-options") || {};
                        var editor = $(this);
                        var format = typeof options.format !== 'undefined' ? options.format : Config.markdown.format;
                        if (format === 'html') {
                            var origin = editor;
                            var turndownService = new TurndownService();
                            turndownService.use(turndownPluginGfm.gfm);
                            var content = turndownService.turndown(origin.val());

                            editor = origin.clone().removeAttr("name").removeAttr("id").val(content);
                            origin.css("display", "none");
                            editor.data("markdown-origin", origin);
                            editor.insertAfter(origin);
                        }
                        (function (editor) {
                            editor.markdown($.extend(true, {
                                resize: 'vertical',
                                language: 'zh',
                                iconlibrary: 'fa',
                                autofocus: false,
                                savable: false,
                                additionalButtons: [
                                    [{
                                        name: "groupCustom",
                                        data: [{
                                            name: "cmdUploadImage",
                                            toggle: false,
                                            title: "Upload image",
                                            icon: "fa fa-upload",
                                        }, {
                                            name: "cmdUploadFile",
                                            toggle: false,
                                            title: "Upload file",
                                            icon: "fa fa-cloud-upload",
                                        }, {
                                            name: "cmdSelectImage",
                                            toggle: false,
                                            title: "Select image",
                                            icon: "fa fa-file-image-o",
                                            callback: function (e) {
                                                parent.Fast.api.open("general/attachment/select?element_id=&multiple=true&mimetype=image/*", __('Choose'), {
                                                    callback: function (data) {
                                                        var urlArr = data.url.split(/\,/);
                                                        insert(e, data.url, 'image');
                                                    }
                                                });
                                                return false;
                                            }
                                        }, {
                                            name: "cmdSelectAttachment",
                                            toggle: false,
                                            title: "Select file",
                                            icon: "fa fa-file",
                                            callback: function (e) {
                                                parent.Fast.api.open("general/attachment/select?element_id=&multiple=true&mimetype=*", __('Choose'), {
                                                    callback: function (data) {
                                                        insert(e, data.url, 'file');
                                                    }
                                                });
                                                return false;
                                            }
                                        }]
                                    }]
                                ],
                                onShow: function (e) {
                                    //添加上传图片按钮和上传附件按钮
                                    var imgBtn = $("button[data-handler='bootstrap-markdown-cmdUploadImage']", e.$editor);
                                    var fileBtn = $("button[data-handler='bootstrap-markdown-cmdUploadFile']", e.$editor);
                                    var btnParent = imgBtn.parent();
                                    btnParent.addClass("md-relative");

                                    var upImgBtn = $('<button type="button" class="uploadimage faupload" data-button="image" title="点击上传图片" data-mimetype="image/gif,image/jpeg,image/png,image/jpg,image/bmp,image/webp" data-multiple="true">点击上传图片</button>');
                                    upImgBtn.css(imgBtn.position()).appendTo(btnParent);

                                    var upFileBtn = $('<button type="button" class="uploadfile faupload" data-button="file" title="点击上传附件" data-multiple="true">点击上传附件</button>');
                                    upFileBtn.css(fileBtn.position()).appendTo(btnParent);

                                    upImgBtn.data("upload-success", function (data, ret) {
                                        insert(e, data.url, 'image');
                                    });
                                    upFileBtn.data("upload-success", function (data, ret) {
                                        insert(e, data.url, 'file');
                                    });
                                    Form.events.faupload(e.$editor);

                                    $(".uploadimage,.uploadfile", e.$editor).on("mouseenter", function () {
                                        ($(this).data("button") === 'image' ? imgBtn : fileBtn).addClass("active");
                                    }).on("mouseleave", function () {
                                        ($(this).data("button") === 'image' ? imgBtn : fileBtn).removeClass("active");
                                    });

                                    //粘贴上传
                                    $(e.$textarea).bind('paste', function (event) {
                                        var originalEvent;
                                        originalEvent = event.originalEvent;
                                        if (originalEvent.clipboardData && originalEvent.clipboardData.files.length > 0) {
                                            uploadFiles.call(e, originalEvent.clipboardData.files);
                                            return false;
                                        }
                                    });
                                    //拖拽上传
                                    $(e.$textarea).bind('drop', function (event) {
                                        var originalEvent;
                                        originalEvent = event.originalEvent;
                                        if (originalEvent.dataTransfer && originalEvent.dataTransfer.files.length > 0) {
                                            uploadFiles.call(e, originalEvent.dataTransfer.files);
                                            return false;
                                        }
                                    });
                                },
                                onChange: function (e) {
                                    var origin = $(e.$textarea).data("markdown-origin");
                                    if (origin) {
                                        origin.val(marked(e.$textarea.val()));
                                    }
                                }
                            }, editor.data("markdown-options") || {}));
                        })(editor)
                    });
                });
            }
        } catch (e) {
            console.log(e);
        }

    };
});

require.config({
    paths: {
        'simditor': '../addons/simditor/js/simditor.min',
    },
    shim: {
        'simditor': [
            'css!../addons/simditor/css/simditor.min.css',
        ]
    }
});
require(['form'], function (Form) {
    var _bindevent = Form.events.bindevent;
    Form.events.bindevent = function (form) {
        _bindevent.apply(this, [form]);
        if ($(Config.simditor.classname || '.editor', form).length > 0) {
            //修改上传的接口调用
            require(['upload', 'simditor'], function (Upload, Simditor) {
                var editor, mobileToolbar, toolbar;
                Simditor.locale = 'zh-CN';
                Simditor.list = {};
                toolbar = ['title', 'bold', 'italic', 'underline', 'strikethrough', 'fontScale', 'color', '|', 'ol', 'ul', 'blockquote', 'code', 'table', '|', 'link', 'image', 'hr', '|', 'indent', 'outdent', 'alignment'];
                mobileToolbar = ["bold", "underline", "strikethrough", "color", "ul", "ol"];
                $(Config.simditor.classname || '.editor', form).each(function () {
                    var id = $(this).attr("id");
                    editor = new Simditor({
                        textarea: this,
                        height: isNaN(Config.simditor.height) ? null : parseInt(Config.simditor.height),
                        minHeight: parseInt(Config.simditor.minHeight || 250),
                        toolbar: Config.simditor.toolbar || [],
                        mobileToolbar: Config.simditor.mobileToolbar || [],
                        toolbarFloat: parseInt(Config.simditor.toolbarFloat),
                        placeholder: Config.simditor.placeholder || '',
                        pasteImage: true,
                        defaultImage: Config.__CDN__ + '/assets/addons/simditor/images/image.png',
                        upload: {url: '/'},
                        allowedTags: ['div', 'br', 'span', 'a', 'img', 'b', 'strong', 'i', 'strike', 'u', 'font', 'p', 'ul', 'ol', 'li', 'blockquote', 'pre', 'code', 'h1', 'h2', 'h3', 'h4', 'hr'],
                        allowedAttributes: {
                            div: ['data-tpl', 'data-source', 'data-id'],
                            span: ['data-id']
                        },
                        allowedStyles: {
                            div: ['width', 'height', 'padding', 'background', 'color', 'display', 'justify-content', 'border', 'box-sizing', 'max-width', 'min-width', 'position', 'margin-left', 'bottom', 'left', 'margin', 'float'],
                            p: ['margin', 'color', 'height', 'line-height', 'position', 'width', 'border', 'bottom', 'float'],
                            span: ['text-decoration', 'color', 'margin-left', 'float', 'background', 'padding', 'margin-right', 'border-radius', 'font-size', 'border', 'float'],
                            img: ['vertical-align', 'width', 'height', 'object-fit', 'float', 'margin', 'float'],
                            a: ['text-decoration']
                        }
                    });
                    editor.uploader.on('beforeupload', function (e, file) {
                        Upload.api.send(file.obj, function (data) {
                            var url = Fast.api.cdnurl(data.url);
                            editor.uploader.trigger("uploadsuccess", [file, {success: true, file_path: url}]);
                        });
                        return false;
                    });
                    editor.on("blur", function () {
                        this.textarea.trigger("blur");
                    });
                    if (editor.opts.height) {
                        editor.body.css({height: editor.opts.height, 'overflow-y': 'auto'});
                    }
                    if (editor.opts.minHeight) {
                        editor.body.css({'min-height': editor.opts.minHeight});
                    }
                    Simditor.list[id] = editor;
                });
            });
        }
    }
});

if (Config.modulename === 'index' && Config.controllername === 'user' && ['login', 'register'].indexOf(Config.actionname) > -1 && $("#register-form,#login-form").length > 0 && $(".social-login").length == 0) {
    $("#register-form,#login-form").append(Config.third.loginhtml || '');
}

});